<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">订单结算</h2>
      <el-button @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <div class="checkout-container">
      <!-- 收货地址 -->
      <el-card class="mb-3">
        <template #header>
          <div class="flex-between">
            <span>
              <el-icon><Location /></el-icon>
              收货地址
            </span>
            <el-button type="primary" link @click="showAddressDialog = true">
              管理地址
            </el-button>
          </div>
        </template>
        
        <div v-if="selectedAddress" class="selected-address">
          <div class="address-info">
            <div class="mb-1">
              <span class="name">{{ selectedAddress.name }}</span>
              <span class="phone">{{ selectedAddress.phone }}</span>
              <el-tag v-if="selectedAddress.isDefault" type="success" size="small">默认</el-tag>
            </div>
            <div class="address">
              {{ selectedAddress.detail }}
            </div>
          </div>
          <el-button type="primary" link @click="showAddressDialog = true">更换</el-button>
        </div>
        
        <el-empty v-else description="请选择收货地址">
          <el-button type="primary" @click="showAddressDialog = true">新增地址</el-button>
        </el-empty>
      </el-card>

      <!-- 商品信息 -->
      <el-card class="mb-3">
        <template #header>
          <span>
            <el-icon><Shop /></el-icon>
            {{ merchantInfo.shopName }}
          </span>
        </template>
        
        <div class="goods-list">
          <div v-for="item in cartItems" :key="item.id" class="goods-item">
            <div class="item-info">
              <img v-if="item.image" :src="item.image" :alt="item.name" class="item-image" />
              <div v-else class="item-icon"><el-icon><Food /></el-icon></div>
              <div class="item-details">
                <div class="item-name">{{ item.name }}</div>
                <div v-if="item.remark" class="item-spec">备注：{{ item.remark }}</div>
              </div>
            </div>
            <div class="item-price">
              <div class="price">¥{{ item.price }}</div>
              <div class="quantity">x{{ item.quantity }}</div>
              <div class="subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 配送方式 -->
      <el-card class="mb-3">
        <template #header>
          <span><el-icon><Van /></el-icon>配送方式</span>
        </template>
        
        <el-radio-group v-model="deliveryMethod">
          <el-radio value="standard" class="delivery-option">
            <div class="option-content">
              <div>
                <div class="option-title">标准配送</div>
                <div class="option-desc">预计 30-45 分钟送达</div>
              </div>
              <div class="option-price">¥{{ deliveryFee }}</div>
            </div>
          </el-radio>
          <el-radio value="express" class="delivery-option">
            <div class="option-content">
              <div>
                <div class="option-title">加急配送</div>
                <div class="option-desc">预计 15-25 分钟送达</div>
              </div>
              <div class="option-price">¥{{ (deliveryFee + 5).toFixed(2) }}</div>
            </div>
          </el-radio>
        </el-radio-group>
      </el-card>

      <!-- 订单备注 -->
      <el-card class="mb-3">
        <template #header>
          <span><el-icon><EditPen /></el-icon>订单备注</span>
        </template>
        <el-input
          v-model="orderRemark"
          type="textarea"
          :rows="3"
          placeholder="请输入订单备注（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-card>
    </div>

    <!-- 底部结算栏 -->
    <div class="checkout-footer">
      <div class="amount-summary">
        <div class="amount-item">
          <span>商品金额：</span>
          <span>¥{{ goodsAmount }}</span>
        </div>
        <div class="amount-item">
          <span>配送费：</span>
          <span>¥{{ actualDeliveryFee }}</span>
        </div>
        <div class="amount-total">
          <span>实付金额：</span>
          <span class="total-price">¥{{ totalAmount }}</span>
        </div>
      </div>
      <el-button 
        type="primary" 
        size="large"
        :loading="submitting"
        :disabled="!canSubmit"
        @click="submitOrder"
      >
        提交订单
      </el-button>
    </div>

    <!-- 地址选择弹窗 -->
    <el-dialog v-model="showAddressDialog" title="选择收货地址" width="600px">
      <div class="address-list">
        <div 
          v-for="address in addresses" 
          :key="address.id"
          class="address-option"
          :class="{ active: selectedAddress?.id === address.id }"
          @click="selectAddress(address)"
        >
          <el-radio :model-value="selectedAddress?.id" :value="address.id">
            <div class="address-content">
              <div class="address-header">
                <span class="name">{{ address.name }}</span>
                <span class="phone">{{ address.phone }}</span>
                <el-tag v-if="address.isDefault" type="success" size="small">默认</el-tag>
              </div>
              <div class="address-detail">
                {{ address.detail }}
              </div>
            </div>
          </el-radio>
        </div>
      </div>
      <div class="mt-3">
        <el-button @click="addNewAddress">新增地址</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Location, Shop, Food, Van, EditPen } from '@element-plus/icons-vue'
import { createOrder } from '../../api/order'
import { getAddresses, getDefaultAddress } from '../../api/address'
import { getMerchantById } from '../../api/merchant'

const router = useRouter()
const route = useRoute()

// 响应式数据
const submitting = ref(false)
const showAddressDialog = ref(false)
const deliveryMethod = ref('standard')
const orderRemark = ref('')
const selectedAddress = ref(null)
const merchantInfo = ref({})
const cartItems = ref([])
const deliveryFee = ref(3.00)
const addresses = ref([])  // 地址列表

// 计算属性
const goodsAmount = computed(() => {
  return cartItems.value.reduce((total, item) => total + (item.price * item.quantity), 0).toFixed(2)
})

const actualDeliveryFee = computed(() => {
  const extraFee = deliveryMethod.value === 'express' ? 5 : 0
  return (deliveryFee.value + extraFee).toFixed(2)
})

const totalAmount = computed(() => {
  const goods = parseFloat(goodsAmount.value)
  const delivery = parseFloat(actualDeliveryFee.value)
  return (goods + delivery).toFixed(2)
})

const canSubmit = computed(() => {
  return selectedAddress.value && cartItems.value.length > 0 && !submitting.value
})

// 方法
const goBack = () => router.go(-1)

const selectAddress = (address) => {
  selectedAddress.value = address
  showAddressDialog.value = false
}

const addNewAddress = () => {
  showAddressDialog.value = false
  router.push('/student/address')
}

const submitOrder = async () => {
  if (!canSubmit.value) {
    ElMessage.warning('请检查订单信息')
    return
  }

  try {
    submitting.value = true
    
    const orderData = {
      merchantId: merchantInfo.value.id,
      orderItems: cartItems.value.map(item => ({
        menuItemId: item.id,
        quantity: item.quantity,
        remark: item.remark || ''
      })),
      deliveryAddress: selectedAddress.value.detail,
      deliveryName: selectedAddress.value.name,
      deliveryPhone: selectedAddress.value.phone,
      remark: orderRemark.value
    }

    const response = await createOrder(orderData)
    
    if (response.success) {
      ElMessage.success('订单提交成功')
      cartItems.value = []
      router.push('/student/orders')
    } else {
      ElMessage.error(response.message || '订单提交失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    ElMessage.error('订单提交失败')
  } finally {
    submitting.value = false
  }
}

// 加载地址列表
const loadAddresses = async () => {
  try {
    const response = await getAddresses()
    addresses.value = response.data || []
    
    // 如果没有选中地址，尝试获取默认地址
    if (!selectedAddress.value) {
      const defaultAddr = addresses.value.find(addr => addr.isDefault)
      if (defaultAddr) {
        selectedAddress.value = defaultAddr
      } else if (addresses.value.length > 0) {
        selectedAddress.value = addresses.value[0]
      }
    }
  } catch (error) {
    console.error('加载地址失败:', error)
    ElMessage.error('加载地址失败')
  }
}

// 加载商家信息
const loadMerchantInfo = async (merchantId) => {
  try {
    const response = await getMerchantById(merchantId)
    merchantInfo.value = response.data || {}
  } catch (error) {
    console.error('加载商家信息失败:', error)
  }
}

const initData = async () => {
  // 从路由参数获取商家ID
  const merchantId = route.query.merchantId
  
  if (merchantId) {
    await loadMerchantInfo(merchantId)
  }
  
  // 从购物车或快速下单获取商品信息
  if (route.query.quickOrder) {
    // 快速下单模式，从上一页传递的数据
    const cartData = sessionStorage.getItem('quickOrderCart')
    if (cartData) {
      try {
        cartItems.value = JSON.parse(cartData)
      } catch (error) {
        console.error('解析快速下单数据失败:', error)
      }
    }
  } else {
    // 普通购物车模式
    const cartData = sessionStorage.getItem('cart')
    if (cartData) {
      try {
        const cart = JSON.parse(cartData)
        cartItems.value = cart.items || []
      } catch (error) {
        console.error('解析购物车数据失败:', error)
      }
    }
  }
  
  // 加载地址
  await loadAddresses()
  
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先选择商品')
    router.push('/student')
  }
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.checkout-container {
  max-width: 800px;
  margin: 0 auto;
  padding-bottom: 120px;
}

.selected-address {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-info {
  flex: 1;
}

.name {
  font-weight: 600;
  margin-right: 12px;
}

.phone {
  color: var(--text-regular);
  margin-right: 12px;
}

.address {
  color: var(--text-regular);
}

.goods-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.item-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  object-fit: cover;
}

.item-icon {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-page);
  border-radius: 8px;
}

.item-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.item-spec {
  font-size: 12px;
  color: var(--text-secondary);
}

.item-price {
  text-align: right;
  min-width: 100px;
}

.price {
  font-weight: 600;
  color: var(--primary-color);
}

.quantity {
  font-size: 12px;
  color: var(--text-secondary);
}

.subtotal {
  font-weight: 600;
}

.delivery-option {
  width: 100%;
  margin-bottom: 12px;
}

.option-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.option-title {
  font-weight: 600;
}

.option-desc {
  font-size: 12px;
  color: var(--text-secondary);
}

.option-price {
  font-weight: 600;
  color: var(--primary-color);
}

.checkout-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid var(--border-light);
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 1000;
}

.amount-summary {
  flex: 1;
  margin-right: 24px;
}

.amount-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 14px;
}

.amount-total {
  display: flex;
  justify-content: space-between;
  padding-top: 8px;
  border-top: 1px solid var(--border-light);
  font-weight: 600;
}

.total-price {
  color: var(--primary-color);
  font-size: 18px;
}

.address-option {
  padding: 16px;
  border: 1px solid var(--border-light);
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
}

.address-option:hover {
  border-color: var(--primary-color);
}

.address-option.active {
  border-color: var(--primary-color);
  background: rgba(64, 158, 255, 0.05);
}

.address-header {
  margin-bottom: 8px;
}

.address-detail {
  color: var(--text-regular);
  font-size: 14px;
}
</style>
